/*
 *    Copyright (c) 2018-2025, boss All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the boss developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: boss
 */

package com.hopes.bizz.risk.hid.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hopes.bizz.common.core.validate.group.AuditGroup;
import com.hopes.bizz.risk.common.constant.HidDicConstant;
import com.hopes.bizz.risk.common.constant.enums.RiskHidSourceEnum;
import com.hopes.bizz.risk.hid.dto.*;
import com.hopes.bizz.risk.hid.entity.RiskHidHiddenDangerEntity;
import com.hopes.bizz.risk.hid.service.RiskHidHiddenDangerFileService;
import com.hopes.bizz.risk.hid.service.RiskHidHiddenDangerService;
import com.hopes.bizz.risk.hid.vo.RiskHidHiddenDangerExcelVO;
import com.hopes.bizz.risk.hid.vo.RiskHidHiddenDangerVO;
import com.hopes.boss.common.core.util.R;
import com.hopes.boss.common.core.util.StringUtils;
import com.hopes.boss.common.core.util.ValidGroup;
import com.hopes.boss.common.excel.annotation.RequestExcel;
import com.hopes.boss.common.excel.annotation.ResponseExcel;
import com.hopes.boss.common.idempotent.annotation.Idempotent;
import com.hopes.boss.common.log.annotation.SysLog;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 隐患信息
 *
 * @author pig
 * @date 2023-07-18 10:51:29
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/hidHiddenDanger")
@Tag(description = "hidHiddenDanger", name = "隐患信息管理")
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
@Slf4j
public class RiskHidHiddenDangerController {

    private final RiskHidHiddenDangerService hidHiddenDangerService;

    /**
     * 分页查询
     *
     * @param page            分页对象
     * @param hidHiddenDanger 隐患信息
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_view')")
    public R queryPage(Page<RiskHidHiddenDangerEntity> page, RiskHidHiddenDangerEntity hidHiddenDanger) {
        return R.ok(hidHiddenDangerService.lambdaQuery()
                .like(StringUtils.isNotBlank(hidHiddenDanger.getHidName()), RiskHidHiddenDangerEntity::getHidName, hidHiddenDanger.getHidName())
                .eq(ObjectUtil.isNotNull(hidHiddenDanger.getHidSource()), RiskHidHiddenDangerEntity::getHidSource, hidHiddenDanger.getHidSource())
                .eq(ObjectUtil.isNotNull(hidHiddenDanger.getHidLevel()), RiskHidHiddenDangerEntity::getHidLevel, hidHiddenDanger.getHidLevel())
                .eq(ObjectUtil.isNotNull(hidHiddenDanger.getHidStatus()), RiskHidHiddenDangerEntity::getHidStatus, hidHiddenDanger.getHidStatus())
                .eq(ObjectUtil.isNotNull(hidHiddenDanger.getReportUserId()), RiskHidHiddenDangerEntity::getReportUserId, hidHiddenDanger.getReportUserId())
                .eq(ObjectUtil.isNotNull(hidHiddenDanger.getCorrectiveUserId()), RiskHidHiddenDangerEntity::getCorrectiveUserId, hidHiddenDanger.getCorrectiveUserId())
                .page(page).convert(RiskHidHiddenDangerVO::new));
    }

    @Operation(summary = "分页查询隐患上报数据", description = "分页查询隐患上报数据")
    @GetMapping("/page/dangerReport")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_view')")
    public R getHidHiddenDangerReportPage(Page<RiskHidHiddenDangerEntity> page, RiskHidHiddenDangerEntity hidHiddenDanger) {
        return R.ok(hidHiddenDangerService.lambdaQuery(hidHiddenDanger).page(page).convert(RiskHidHiddenDangerVO::new));
    }

    /**
     * 通过id查询隐患信息
     *
     * @param id
     * @return R
     */
    @Operation(summary = "通过id查询", description = "通过id查询")
    @GetMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_view')")
    public R getById(@PathVariable("id") Long id) {
        RiskHidHiddenDangerEntity hiddenDangerEntity = hidHiddenDangerService.getById(id);
        RiskHidHiddenDangerVO riskHidHiddenDangerVO = new RiskHidHiddenDangerVO(hiddenDangerEntity);
        return R.ok(riskHidHiddenDangerVO);
    }


    /**
     * 通过id删除隐患信息
     *
     * @param ids id列表
     * @return R
     */
    @Operation(summary = "通过id删除隐患信息", description = "通过id删除隐患信息")
    @SysLog("通过id删除隐患信息")
    @DeleteMapping
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_del')")
    public R removeById(@RequestBody Long[] ids) {
        hidHiddenDangerService.deleteTask(CollUtil.toList(ids));
        return R.ok();
    }


    /**
     * excel模板
     *
     * @return excel 文件流
     */
    @ResponseExcel
    @GetMapping("/template")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_export')")
    public List<RiskHidHiddenDangerExcelVO> template() {
        return hidHiddenDangerService.exportExcel(Arrays.asList(new RiskHidHiddenDangerEntity()));
    }

    /**
     * 导入excel 表格
     *
     * @param hidHiddenDangerExcelDtoList 查询条件
     * @param bindingResult               错误信息列表
     * @return ok fail
     */
    @PostMapping("/import")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_import')")
    public R importExcel
    (@RequestExcel List<RiskHidHiddenDangerExcelDTO> hidHiddenDangerExcelDtoList, BindingResult bindingResult) {
        return hidHiddenDangerService.importExcel(hidHiddenDangerExcelDtoList, bindingResult);
    }

    /**
     * 查询逾期隐患记录列表
     */
    @GetMapping(value = "overdueList")
    public R overdueList(RiskHidHiddenDangerEntity hidHiddenDanger, Page<RiskHidHiddenDangerEntity> page) {
        LambdaQueryWrapper<RiskHidHiddenDangerEntity> wrapper = new LambdaQueryWrapper<>();
        // 隐患来源，隐患等级，隐患类型，状态
        wrapper.eq(ObjectUtil.isNotEmpty(hidHiddenDanger.getHidSource()), RiskHidHiddenDangerEntity::getHidSource, hidHiddenDanger.getHidSource())
                .eq(ObjectUtil.isNotEmpty(hidHiddenDanger.getHidLevel()), RiskHidHiddenDangerEntity::getHidLevel, hidHiddenDanger.getHidLevel())
                .eq(ObjectUtil.isNotEmpty(hidHiddenDanger.getHidType()), RiskHidHiddenDangerEntity::getHidType, hidHiddenDanger.getHidType())
                .eq(RiskHidHiddenDangerEntity::getHidStatus, HidDicConstant.HID_DANGER_WAIT_RECTIFICATION)
                .le(RiskHidHiddenDangerEntity::getCorrectiveDeadline, new Date())
                .orderByDesc(RiskHidHiddenDangerEntity::getReportDate);
        Page<RiskHidHiddenDangerEntity> res = hidHiddenDangerService.page(page, wrapper);
        return R.ok(res);
    }

    /**
     * @Description 隐患新增
     **/
    @SysLog("新增隐患信息")
    @Operation(summary = "新增隐患信息", description = "新增隐患信息")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_add')")
    @PostMapping(value = "handleHidSave")
    public R handleHidSave(@Validated(ValidGroup.Insert.class) @RequestBody RiskHidHiddenDangerDTO
                                   riskHidHiddenDangerDTO) {
        // 隐患源编码（主动上报）
        riskHidHiddenDangerDTO.setBizCode(RiskHidSourceEnum.HID_REPORT.getCode());
        riskHidHiddenDangerDTO.setBizName(RiskHidSourceEnum.HID_REPORT.getName());
        hidHiddenDangerService.handleHidSave(riskHidHiddenDangerDTO);
        return R.ok();
    }

    /**
     * @Description 隐患更新
     **/
    @Operation(summary = "修改隐患信息", description = "修改隐患信息")
    @SysLog("修改隐患信息")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_edit')")
    @PostMapping(value = "handleHidUpdate")
    public R handleHidUpdate(@Validated(ValidGroup.Update.class) @RequestBody RiskHidHiddenDangerDTO
                                     riskHidHiddenDangerDTO) {
        hidHiddenDangerService.handleHidUpdate(riskHidHiddenDangerDTO);
        return R.ok();
    }

    /**
     * @Description 隐患新增并提交
     * @Author lyb
     * @Date 2023/3/16
     **/
    @SysLog("新增隐患并提交")
    @Operation(summary = "新增隐患并提交", description = "新增隐患并提交")
    @Idempotent(expireTime = 5, info = "请勿重复提交")
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_add')")
    @PostMapping(value = "handleHidSaveAndSubmit")
    public R handleHidSaveAndSubmit(@Validated(ValidGroup.Insert.class) @RequestBody RiskHidHiddenDangerDTO
                                            riskHidHiddenDangerDTO) {
        riskHidHiddenDangerDTO.setBizCode(RiskHidSourceEnum.HID_REPORT.getCode());
        riskHidHiddenDangerDTO.setBizName(RiskHidSourceEnum.HID_REPORT.getName());
        hidHiddenDangerService.handleHidSaveAndSubmit(riskHidHiddenDangerDTO);
        return R.ok();
    }

    /**
     * @Description 隐患提交
     * @Author lyb
     * @Date 2023/3/16
     **/
    @Operation(summary = "隐患提交", description = "隐患提交")
    @SysLog("隐患提交")
    @Idempotent(key = "#id", expireTime = 5, info = "请勿重复提交")
    @GetMapping(value = "handleHidSubmit/{id}")
    public R handleHidSubmit(@PathVariable Long id) {
        hidHiddenDangerService.handleHidSubmit(id);
        return R.ok();
    }

    /**
     * @Description 隐患确认
     * @Author lyb
     * @Date 2023/3/16
     **/
    @Operation(summary = "隐患确认", description = "隐患确认")
    @SysLog("隐患确认")
    @Idempotent(key = "#handleHidConfirmDto.id", expireTime = 5, info = "请勿重复提交")
    @PostMapping(value = "handleHidConfirm")
    public R handleHidConfirm(@Validated(AuditGroup.class) @RequestBody RiskHandleHidConfirmDTO handleHidConfirmDto) {
        hidHiddenDangerService.handleHidConfirm(handleHidConfirmDto);
        return R.ok();
    }

    /**
     * @Description 隐患整改
     * @Author lyb
     * @Date 2023/3/16
     **/
    @Operation(summary = "隐患整改", description = "隐患整改")
    @SysLog("隐患整改")
    @Idempotent(key = "#handleHidRectifyDto.id", expireTime = 5, info = "请勿重复提交")
    @PostMapping(value = "handleHidRectify")
    public R handleHidRectify(@Validated(AuditGroup.class) @RequestBody RiskHandleHidRectifyDTO handleHidRectifyDto) {
        hidHiddenDangerService.handleHidRectify(handleHidRectifyDto);
        return R.ok();
    }

    /**
     * @Description 隐患验收
     * @Author lyb
     * @Date 2023/3/16
     **/
    @Operation(summary = "隐患验收", description = "隐患验收")
    @SysLog("隐患验收")
    @Idempotent(key = "#handleHidAcceptanceDto.id", expireTime = 5, info = "请勿重复提交")
    @PostMapping(value = "handleHidAcceptance")
    public R handleHidAcceptance(@Validated(AuditGroup.class) @RequestBody RiskHandleHidAcceptanceDTO
                                         handleHidAcceptanceDto) {
        hidHiddenDangerService.handleHidAcceptance(handleHidAcceptanceDto);
        return R.ok();
    }

    /**
     * 导出excel 表格
     *
     * @param riskHidHiddenDangerExcelDTO 查询条件
     * @return excel 文件流
     */
    @GetMapping(value = "export")
    @ResponseExcel
    @PreAuthorize("@pms.hasPermission('hid_hidden_danger_export')")
    public void export(RiskHidHiddenDangerExcelDTO riskHidHiddenDangerExcelDTO, HttpServletResponse response) {
        try (ServletOutputStream out = response.getOutputStream()) {
            SpringUtil.getBean(riskHidHiddenDangerExcelDTO.getExportType(), RiskHidHiddenDangerFileService.class).exportList(riskHidHiddenDangerExcelDTO, out);
        } catch (Exception ex) {
            log.error("导出隐患信息", ex);
        }
    }

    @Operation(summary = "隐患确认列表-待确认", description = "隐患确认列表-待确认")
    @GetMapping("/listWaitConfirm")
    public R listWaitConfirm(RiskHidHiddenDangerFlowSearchDTO flowSearch, Page<RiskHidHiddenDangerEntity> page) {
        return R.ok(hidHiddenDangerService.queryTodoForPage(page, HidDicConstant.HID_DANGER_STATUS_WAIT_CONFIRM.toString(), flowSearch)
                .convert(RiskHidHiddenDangerVO::new));
    }


    @Operation(summary = "查询我的待整改", description = "查询我的待整改")
    @GetMapping("/listWaitRectify")
    public R listWaitRectify(RiskHidHiddenDangerFlowSearchDTO flowSearch, Page<RiskHidHiddenDangerEntity> page) {
        return R.ok(hidHiddenDangerService.queryTodoForPage(page, HidDicConstant.HID_DANGER_WAIT_RECTIFICATION.toString(), flowSearch)
                .convert(RiskHidHiddenDangerVO::new));
    }


    @Operation(summary = "查询我的待验收", description = "查询我的待验收")
    @GetMapping("/listWaitCheck")
    public R listWaitCheck(RiskHidHiddenDangerFlowSearchDTO flowSearch, Page<RiskHidHiddenDangerEntity> page) {
        return R.ok(hidHiddenDangerService.queryTodoForPage(page, HidDicConstant.HID_DANGER_STATUS_WAIT_ACCEPTANCE.toString(), flowSearch)
                .convert(RiskHidHiddenDangerVO::new));
    }

}
